package com.punai.prodatalibrary.controller;

import cn.hutool.core.util.ObjectUtil;
import com.punai.common.annotation.Log;
import com.punai.common.bos.KVBO;
import com.punai.common.config.RuoYiConfig;
import com.punai.common.core.controller.BaseController;
import com.punai.common.core.domain.AjaxResult;
import com.punai.common.core.page.TableDataInfo;
import com.punai.common.enums.BusinessType;
import com.punai.common.exception.ServiceException;
import com.punai.common.utils.poi.ExcelUtil;
import com.punai.externalccb.constants.CCBConstants;
import com.punai.prodatalibrary.domain.LibProject;
import com.punai.prodatalibrary.domain.LibProjectInfo;
import com.punai.prodatalibrary.domain.ProjectInfoAttachment;
import com.punai.prodatalibrary.domain.SearchInfo;
import com.punai.prodatalibrary.domain.bo.GlobalProInfoBo;
import com.punai.prodatalibrary.domain.bo.ProUserBo;
import com.punai.prodatalibrary.domain.bo.ProjectInfoAttachmentBo;
import com.punai.prodatalibrary.domain.vo.SetProUserListVo;
import com.punai.prodatalibrary.service.ILibProjectInfoService;
import com.punai.prodatalibrary.service.ILibProjectService;
import com.punai.prodatalibrary.service.IProjectInfoAttachmentService;
import io.netty.util.internal.StringUtil;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 项目基本信息Controller
 * 
 * @author tj
 * @date 2023-03-31
 */
@RestController
@RequestMapping("/prodatalibrary/projectBasicInfo")
public class LibProjectInfoController extends BaseController
{
    @Autowired
    private ILibProjectInfoService libProjectInfoService;

    @Autowired
    private IProjectInfoAttachmentService projectInfoAttachmentService;

    @Autowired
    private ILibProjectService libProjectService;

    /**
     * 查询项目基本信息列表
     */
    @PreAuthorize("@ss.hasPermi('prodatalibrary:projectBasicInfo:list')")
    @GetMapping("/list")
    public TableDataInfo list(GlobalProInfoBo globalProInfoBo) {
        logger.info("接口请求进来了");
        startPage();
        return libProjectInfoService.selectInfoListSize(globalProInfoBo);
    }

    /**
     * 获取项目基本信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('prodatalibrary:projectBasicInfo:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return AjaxResult.success(libProjectInfoService.selectLibProjectInfoById(id));
    }

    /**
     * 新增项目基本信息
     */
    @PreAuthorize("@ss.hasPermi('prodatalibrary:projectBasicInfo:add')")
    @Log(title = "项目基本信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody LibProjectInfo libProjectInfo)
    {
        return toAjax(libProjectInfoService.insertLibProjectInfo(libProjectInfo));
    }

    /**
     * 修改项目基本信息
     */
    @PreAuthorize("@ss.hasPermi('prodatalibrary:projectBasicInfo:edit')")
    @Log(title = "项目基本信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody LibProjectInfo libProjectInfo)
    {
        return toAjax(libProjectInfoService.updateLibProjectInfo(libProjectInfo));
    }

    /**
     * 删除项目基本信息
     */
    @PreAuthorize("@ss.hasPermi('prodatalibrary:projectBasicInfo:remove')")
    @Log(title = "项目基本信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        return toAjax(libProjectInfoService.deleteLibProjectInfoByIds(ids));
    }

    /**
     * 获取所有项目公司
     */
    @PreAuthorize("@ss.hasPermi('prodatalibrary:projectBasicInfo:query')")
    @GetMapping("/groupByDeptOfProject")
    public AjaxResult groupByDeptOfProject()
    {
        return AjaxResult.success(libProjectInfoService.groupByDeptOfProject());
    }

    /**
     * 获取所有项目类型
     */
    @PreAuthorize("@ss.hasPermi('prodatalibrary:projectBasicInfo:query')")
    @GetMapping("/groupByProjectState")
    public AjaxResult groupByProjectState()
    {
        return AjaxResult.success(libProjectInfoService.groupByProjectState());
    }

    /**
     * 获取所有项目类型
     */
    @PreAuthorize("@ss.hasPermi('prodatalibrary:projectBasicInfo:list')")
    @GetMapping("/projectInfoAttachment")
    public TableDataInfo projectInfoAttachment(ProjectInfoAttachmentBo projectInfoAttachment)
    {
        String type = projectInfoAttachment.getType();
        List<String> types = new ArrayList<>();
        if (type.equals("1")){
        }else if (type.equals("2")){
            types.add("02");types.add("04");
        }else if (type.equals("3")){
            types.add("06");types.add("07");types.add("08");
        }
        projectInfoAttachment.setTypes(types);
        LibProjectInfo libProjectInfo = libProjectInfoService.selectLibProjectInfoById(projectInfoAttachment.getProjectId());
        if (ObjectUtil.isNotEmpty(libProjectInfo)) projectInfoAttachment.setProjectId(libProjectInfo.getProId());
        startPage();
        List<ProjectInfoAttachment> projectInfoAttachments = projectInfoAttachmentService.selectAttachmentList(projectInfoAttachment);
        for (ProjectInfoAttachment attachment : projectInfoAttachments) {
            String desc = CCBConstants.CCB_TYPE.getDescByCode(attachment.getAttachmentType());
            attachment.setAttachmentType(desc);
        }
        return getDataTable(projectInfoAttachments);
    }

    /**
     * 下载附件
     */
    @PreAuthorize("@ss.hasPermi('prodatalibrary:projectBasicInfo:download')")
    @PostMapping("/downloadFile")
    public void downloadFile(String id,HttpServletResponse response) throws Exception {
        if(StringUtil.isNullOrEmpty(id)) {
            throw new Exception("error");
        }

        ProjectInfoAttachment projectInfoAttachments = projectInfoAttachmentService.selectAttachmentById(id);
        if (ObjectUtil.isNull(projectInfoAttachments)){
            throw new Exception("error");
        }
        String localFilePath = projectInfoAttachments.getLocalFilePath();
        FileInputStream inputStream = null;
        try {
            inputStream = new FileInputStream(new File(localFilePath));
            downloadFile(inputStream,response);
        } catch (FileNotFoundException e) {
            throw new ServiceException(e.getMessage());
        }
    }

    /**
     * 下载标识附件
     */
    @PreAuthorize("@ss.hasPermi('prodatalibrary:projectBasicInfo:download')")
    @PostMapping("/downloadxml")
    public void downloadxml(String id,HttpServletResponse response) throws Exception {
        if(StringUtil.isNullOrEmpty(id)) {
            throw new Exception("error");
        }
        LibProject libProject = libProjectService.selectLibProjectById(id);
        Document doc = DocumentHelper.createDocument();
        //2.创建根元素
        Element xmxx = doc.addElement("项目信息");
        xmxx.addAttribute("ID", libProject.getId());
        //3.创建子元素
        Element xmmc = xmxx.addElement("项目名称");
        Element xmbh = xmxx.addElement("项目编号");
        xmmc.addText(libProject.getName());
        xmbh.addText(libProject.getCode());
        String downFileName = "xml_" + DateFormatUtils.format(new Date(), "yyyyMMddHHmmssSSS")+"_"+libProject.getId() + ".xml";
        // 本地资源路径
        String localPath = RuoYiConfig.getProfile();
        File downFile = new File(localPath,downFileName);
        OutputFormat format = OutputFormat.createPrettyPrint();
        XMLWriter os = null;
        FileInputStream inputStream = null ;
        OutputStream out = null;
        try {
            out = new FileOutputStream(downFile);
            Writer wr = new OutputStreamWriter(out, "UTF-8");
            os = new XMLWriter(wr, format);
            os.write(doc);
            os.close();
            String xmlFileName = libProject.getName()+"-"+libProject.getCode()+".xml";
            inputStream = new FileInputStream(new File(localPath,downFileName));
            if ( inputStream != null ) {
                this.downloadFile(inputStream, response);
            }
        }catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(null != os) {
                    os.close();
                }
                if(inputStream != null) {
                    inputStream.close();
                }
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @PreAuthorize("@ss.hasPermi('prodatalibrary:projectBasicInfo:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, GlobalProInfoBo globalProInfoBo)
    {
        List<LibProjectInfo> list = libProjectInfoService.selectProjectList(globalProInfoBo);
        ExcelUtil<LibProjectInfo> util = new ExcelUtil<LibProjectInfo>(LibProjectInfo.class);
        util.exportExcel(response, list, "项目基本信息");
    }

    @GetMapping("/getAllAddress")
    public AjaxResult getAllAddress()
    {
        List<KVBO> list = libProjectInfoService.getAllAddress();
        return AjaxResult.success(list);
    }

    @GetMapping("/searchJson")
    public AjaxResult searchJson()
    {
        List<SearchInfo> json = libProjectInfoService.searchJson();
        return AjaxResult.success(json);
    }


    @GetMapping("/getProUserList/{proId}")
    public AjaxResult getProUserList(@PathVariable String proId) {
        ProUserBo proUserBo = libProjectInfoService.getProUserList(proId);
        return AjaxResult.success(proUserBo);
    }

    @PostMapping("/saveProUserList")
    public AjaxResult saveProUserList(@RequestBody SetProUserListVo vo) {
        libProjectInfoService.saveProUserList(vo);
        return AjaxResult.success();
    }


}
